package top.linyuxb.lycloud.common.common;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import top.linyuxb.lycloud.common.mapper.LyConfigServerMapper;
import top.linyuxb.lycloud.common.po.LyConfigServerPo;
import top.linyuxb.lycloud.common.properties.LyConfigProperties;
import top.linyuxb.lycloud.common.utils.InetAddressUtil;

import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by Intellij IDEA.
 *
 * @Author: linyuxb
 * @Date: 2024/7/31 17:19
 * @Desc:
 */
@Slf4j
public class LyConfigServerService {
    /**
     * 存放注册中心 数据库id
     */
    private static final List<Long> dbIdList = new ArrayList<>();

    /**
     * 注册服务 续命
     *
     * @param lyRpcClientProperties
     * @param port
     */
    public static void register(LyConfigProperties lyRpcClientProperties, String port) {
        // 1、缓存id存在，更新注册信息
        if (!dbIdList.isEmpty()) {
            doUpdate(lyRpcClientProperties);
            return;
        }

        String address = InetAddressUtil.getIpAddress(lyRpcClientProperties.getRegisterType());
        String sql = """
                    SELECT * FROM ly_conf_server where `env` = ? and `app` = ? and `server_ip` = ? and `server_port` = ?
                    order by `id` desc limit 1;
                """;
        List<LyConfigServerPo> lyConfigNodePos = LyConfigJdbcService.getJdbcTemplate()
                .query(sql,
                        new Object[]{lyRpcClientProperties.getEnv(), lyRpcClientProperties.getApp(), address, port},
                        new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR},
                        new LyConfigServerMapper());
        //2、没有记录、新增注册信息
        if (CollUtil.isEmpty(lyConfigNodePos)) {
            String saveSql = """
                        INSERT INTO ly_conf_server (`env`,`app`,`server_ip`,`server_port`,`user`,`user_password`,`active`,`weight`,`status`)
                        VALUES ( ?, ?, ?, ?, ?, ?, ?, ?,'1');
                    """;
            int update = LyConfigJdbcService.getJdbcTemplate().update(saveSql,
                    new Object[]{lyRpcClientProperties.getEnv(), lyRpcClientProperties.getApp(), address, port,
                            lyRpcClientProperties.getUser(), lyRpcClientProperties.getUserPassword(),
                            DateUtil.offsetMinute(DateUtil.date(), lyRpcClientProperties.getActive()), lyRpcClientProperties.getWeight()},
                    new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.TIMESTAMP, Types.INTEGER}
            );
            if (update < 1) {
                log.error("[LyConfigService register] [INSERT error]");
            }
            return;
        }

        // 3、存在记录，缓存id，更新注册信息
        dbIdList.add(0, lyConfigNodePos.get(0).getId());
        doUpdate(lyRpcClientProperties);
    }

    /**
     * 执行服务更新
     *
     * @param lyRpcClientProperties
     */
    private static void doUpdate(LyConfigProperties lyRpcClientProperties) {
        String editSql = """
                    UPDATE ly_conf_server set `user` = ?, `user_password` = ? ,`active` = ? where `id` = ? ;
                """;
        int update = LyConfigJdbcService.getJdbcTemplate().update(editSql,
                new Object[]{lyRpcClientProperties.getUser(), lyRpcClientProperties.getUserPassword(),
                        DateUtil.offsetMinute(DateUtil.date(), lyRpcClientProperties.getActive()), dbIdList.get(0)},
                new int[]{Types.VARCHAR, Types.VARCHAR, Types.TIMESTAMP, Types.BIGINT}
        );
        if (update < 1) {
            log.error("[LyConfigService register] [UPDATE error]");
        }
    }

    /**
     * 获取全量有效服务
     *
     * @param env
     * @return
     */
    public static Map<String, List<LyConfigServerPo>> getServers(String env) {
        String sql = """
                    select * from ly_conf_server where `env` = ? and `status` = 1 and `active` > now();
                """;
        List<LyConfigServerPo> lyConfigNodePos = LyConfigJdbcService.getJdbcTemplate()
                .query(sql,
                        new Object[]{env},
                        new int[]{Types.VARCHAR},
                        new LyConfigServerMapper());
        return lyConfigNodePos.stream()
                .collect(Collectors.groupingBy(LyConfigServerPo::getApp));
    }


}
